package com.itheima.stock.service.impl;

import com.alibaba.fastjson2.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import com.itheima.stock.entity.StockBlockRtInfo;
import com.itheima.stock.entity.StockBusiness;
import com.itheima.stock.entity.StockMarketIndexInfo;
import com.itheima.stock.entity.StockRtInfo;
import com.itheima.stock.mapper.StockBlockRtInfoMapper;
import com.itheima.stock.mapper.StockBusinessMapper;
import com.itheima.stock.mapper.StockMarketIndexInfoMapper;
import com.itheima.stock.mapper.StockRtInfoMapper;
import com.itheima.stock.properties.MarketIndexProperties;
import com.itheima.stock.service.StockTimerService;
import com.itheima.stock.util.IdWorkers;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @version 1.0
 * @Author lwx
 * @Date 2024/12/28 19:39
 */
@Service
public class StockTimerServiceImpl implements StockTimerService {

    private final RestTemplate restTemplate;

    private final IdWorkers idWorkers;

    private final StockMarketIndexInfoMapper stockMarketIndexInfoMapper;

    private final MarketIndexProperties marketIndexProperties;
    private final StockBusinessMapper stockBusinessMapper;
    private final StockRtInfoMapper stockRtInfoMapper;
    private final StockBlockRtInfoMapper stockBlockRtInfoMapper;

    public StockTimerServiceImpl(RestTemplate restTemplate, IdWorkers idWorkers, StockMarketIndexInfoMapper stockMarketIndexInfoMapper, MarketIndexProperties marketIndexProperties, StockBusinessMapper stockBusinessMapper, StockRtInfoMapper stockRtInfoMapper, StockBlockRtInfoMapper stockBlockRtInfoMapper) {
        this.restTemplate = restTemplate;
        this.idWorkers = idWorkers;
        this.stockMarketIndexInfoMapper = stockMarketIndexInfoMapper;
        this.marketIndexProperties = marketIndexProperties;
        this.stockBusinessMapper = stockBusinessMapper;
        this.stockRtInfoMapper = stockRtInfoMapper;
        this.stockBlockRtInfoMapper = stockBlockRtInfoMapper;
    }

    @Override
    public void getInnerMarketInfo() {
        //使用RestTemplate调用接口

        String url = "https://hq.sinajs.cn/list";

        List<String> ids = marketIndexProperties.getInner();

        StringBuilder stringBuilder = new StringBuilder();

        for (int i = 0; i < ids.size(); i++) {
            String id = ids.get(i);
            if (i == ids.size() - 1){
                stringBuilder.append(id);
            }else {
                stringBuilder.append(id).append(",");
            }
        }

        String urls = String.join("=", url, stringBuilder.toString());

        HttpMethod method = HttpMethod.GET;

        HttpHeaders header = new HttpHeaders();
        header.add("Referer","https://finance.sina.com.cn/stock/");
        header.add("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36");

        HttpEntity<?> entity = new HttpEntity<>(header);

        ResponseEntity<String> response = restTemplate.exchange(urls, method, entity, String.class);
        // 使用正则处理数据
        String body = response.getBody();

        String regex = "var hq_str_(.+)=\"(.+)\";";

        Pattern compile = Pattern.compile(regex);
        Matcher matcher = compile.matcher(body);
        List<StockMarketIndexInfo> lists = new ArrayList<>();
        while (matcher.find()){
            String code = matcher.group(1);
            String resStr = matcher.group(2);
            String[] resArr = resStr.split(",");
            String market_name = resArr[0];
            String cur_point_str = resArr[1];
            BigDecimal cur_point = BigDecimal.valueOf(Double.parseDouble(cur_point_str));
            String current_price_str = resArr[2];
            BigDecimal current_price = BigDecimal.valueOf(Double.parseDouble(current_price_str));
            String updown_rate_str = resArr[3];
            BigDecimal updown_rate = BigDecimal.valueOf(Double.parseDouble(updown_rate_str));
            String trade_amount_str = resArr[4];
            Long trade_amount = Long.valueOf(trade_amount_str);
            String trade_volume_str = resArr[5];
            Long trade_volume = Long.valueOf(trade_volume_str);

            StockMarketIndexInfo stockMarketIndexInfo = StockMarketIndexInfo.builder()
                    .id(idWorkers.nextStrId())
                    .markId(code)
                    .markName(market_name)
                    .currentPrice(current_price)
                    .curPoint(cur_point)
                    .tradeAccount(trade_amount)
                    .tradeVolume(trade_volume)
                    .updownRate(updown_rate)
                    .curTime(LocalDateTime.now())
                    .build();
            lists.add(stockMarketIndexInfo);

        }

        stockMarketIndexInfoMapper.insertBatch(lists);

    }

    @Override
    public void getStockInfo() {

        String urls = "https://hq.sinajs.cn/list";

        List<StockBusiness> stockBusinesses = stockBusinessMapper.selectAll();

        List<String> sec_code_list = stockBusinesses.stream().map((business) -> {
            if (business.getSecCode().startsWith("00")) {
                return String.join("" ,"sz",business.getSecCode());
            } else if (business.getSecCode().startsWith("60")) {
                return String.join("","sh", business.getSecCode());
            } else {
                return null;
            }
        }).toList();

        String param = String.join(",", sec_code_list);

        String url = String.join("=", urls, param);
        HttpMethod method = HttpMethod.GET;

        HttpHeaders header = new HttpHeaders();
        header.add("Referer","https://finance.sina.com.cn/stock/");
        header.add("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36");

        HttpEntity<?> entity = new HttpEntity<>(header);

        ResponseEntity<String> response = restTemplate.exchange(url, method, entity, String.class);

        // 使用正则处理数据
        String body = response.getBody();

        String regex="var hq_str_[a-z][a-z](\\d.+)=\"(.+)\";";

        Pattern compile = Pattern.compile(regex);
        Matcher matcher = compile.matcher(body);
        // 5000个数据
        List<StockRtInfo> lists = Lists.newArrayList();
        while (matcher.find()){
            String stock_code = matcher.group(1);
            String resStr =matcher.group(2);
            String[] resArr = resStr.split( ",");
            String stock_name = resArr[0];
            String open_price_str = resArr[1];
            BigDecimal open_price = BigDecimal.valueOf(Double.parseDouble(open_price_str));
            String pre_close_price_str = resArr[2];
            BigDecimal pre_close_price = new BigDecimal (pre_close_price_str);
            String cur_price_str = resArr[3];
            BigDecimal cur_price = new BigDecimal(cur_price_str);
            String max_price_str = resArr[4];
            BigDecimal max_price = new BigDecimal(max_price_str);
            String min_price_str = resArr[5];
            BigDecimal min_price = new BigDecimal(min_price_str);
            String trade_amount_str =resArr[8];
            Long trade_amount = Long.parseLong(trade_amount_str);
            String trade_volume_str = resArr[9];
            BigDecimal trade_volume = new BigDecimal(trade_volume_str);
            String date_str = resArr[30];
            String time_str = resArr[31];
            String date_time_str = String.join(" ", date_str, time_str);
            LocalDateTime curTime = LocalDateTime.parse(date_time_str, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

            StockRtInfo stockRtInfo = StockRtInfo.builder()
                    .stockCode(stock_code)
                    .stockName(stock_name)
                    .openPrice(open_price)
                    .preClosePrice(pre_close_price)
                    .curPrice(cur_price)
                    .maxPrice(max_price)
                    .minPrice(min_price)
                    .tradeAmount(trade_amount)
                    .tradeVolume(trade_volume)
                    .curTime(curTime)
                    .id(idWorkers.nextStrId())
                    .build();

            lists.add(stockRtInfo);
        }

        Lists.partition(lists, 10).forEach(stockRtInfoMapper::insertBatch);


    }

    @Override
    public void getStockBlockInfo() {
        String url = "https://vip.stock.finance.sina.com.cn/q/view/newSinaHy.php";

        HttpMethod method = HttpMethod.GET;

        HttpHeaders header = new HttpHeaders();
        header.add("Referer","https://finance.sina.com.cn/stock/");
        header.add("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36");

        HttpEntity<?> entity = new HttpEntity<>(header);

        ResponseEntity<String> response= restTemplate.exchange(url, method, entity, String.class);

        String body = response.getBody();

        String regex = "var S_Finance_bankuai_sinaindustry = (.+)";

        Pattern compile = Pattern.compile(regex);
        Matcher matcher = compile.matcher(body);

        List<StockBlockRtInfo> lists = Lists.newArrayList();

        while (matcher.find()){
            String jsonStr = matcher.group(1);
            Map map = JSON.parseObject(jsonStr, Map.class);
            System.out.println(map);
            Collection values = map.values();
            for (Object valueStr : values) {
                String value = valueStr.toString();
                String[] resArr = value.split(",");
                String label = resArr[0];
                String block_name = resArr[1];
                String company_num_str = resArr[2];
                Integer company_num = Integer.valueOf(company_num_str);
                String avg_price_str = resArr[3];
                BigDecimal avg_price = new BigDecimal(avg_price_str);
                String updown_rate_str = resArr[5];
                BigDecimal updown_rate = new BigDecimal(updown_rate_str);
                String trade_amount_str = resArr[6];
                Long trade_amount = Long.parseLong(trade_amount_str);
                String trade_volume_str = resArr[7];
                BigDecimal trade_volume = new BigDecimal(trade_volume_str);

                StockBlockRtInfo stockBlockRtInfo = StockBlockRtInfo.builder()
                        .id(idWorkers.nextStrId())
                        .label(label)
                        .blockName(block_name)
                        .avgPrice(avg_price)
                        .updownRate(updown_rate)
                        .tradeAmount(trade_amount)
                        .tradeVolume(trade_volume)
                        .companyNum(company_num)
                        .curTime(LocalDateTime.now())
                        .build();

                lists.add(stockBlockRtInfo);
            }
        }
        stockBlockRtInfoMapper.insertBatch(lists);

    }
}
